package com.tanhua.dubbo.api.impl.mongo;

import com.alibaba.fastjson.JSON;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.FreezingUser;
import com.tanhua.domain.mongo.UnFreezingUser;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.FreezeApi;
import com.tanhua.dubbo.mapper.UserInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.ObjectUtils;
import java.util.concurrent.TimeUnit;


@Service
@Slf4j
public class FreezeApiImpl implements FreezeApi {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserInfoApi userInfoApi;

    public String getFreezeUserKey(Integer userId) {
        return "FREEZE_USER_" + userId;
    }


    /**
     * 冻结用户操作
     * @param userId             用户Id
     * @param freezingTime       冻结时间，1为冻结3天，2为冻结7天，3为永久冻结
     * @param freezingRange      冻结范围，1为冻结登录，2为冻结发言，3为冻结发布动态
     * @param reasonsForFreezing 冻结原因
     * @param frozenRemarks      冻结备注
     * @return
     * @Author LianQingSen
     */
    @Override
    public String freezeUserById(Integer userId, Integer freezingTime, Integer freezingRange, String reasonsForFreezing, String frozenRemarks) {
        String redisKey = getFreezeUserKey(userId);
        FreezingUser freezingUser = new FreezingUser();
        freezingUser.setId(ObjectId.get());
        freezingUser.setUserId(userId);
        freezingUser.setFreezingTime(freezingTime);
        freezingUser.setFreezingRange(freezingRange);
        freezingUser.setReasonsForFreezing(reasonsForFreezing);
        freezingUser.setFrozenRemarks(frozenRemarks);
        freezingUser.setCreated(System.currentTimeMillis());

        String jsonStr = JSON.toJSONString(freezingUser);
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        switch (freezingTime) {
            case 1: {
                //TODO 为测试数据才设置的20秒
                ops.set(redisKey, jsonStr, 20, TimeUnit.SECONDS);
                break;
            }
            case 2: {
                redisTemplate.opsForValue().set(redisKey, jsonStr, 7, TimeUnit.DAYS);
                break;
            }
            case 3: {
                redisTemplate.opsForValue().set(redisKey, jsonStr);
                break;
            }
            default:
                return null;
        }
        mongoTemplate.save(freezingUser);
        userInfoMapper.updateUserStatusById(userId.longValue(), "2");
        return "seccess";
    }

    /**
     * 用户解冻操作
     * @param userId            解封的用户Id
     * @param reasonsForThawing 解封原因
     * @return
     */
    @Override
    public String unFreezeUser(Integer userId, String reasonsForThawing) {
        String redisKey = getFreezeUserKey(userId);
        //判断是否存在冻结
        UserInfo userInfo = userInfoApi.findById(userId.longValue());
        if (ObjectUtils.isEmpty(userInfo)) {
            return "error";
        }
        if (!redisTemplate.hasKey(redisKey)) {
            if ( userInfo.getUserStatus() == "1"){
                return "error";
            }
        }
        redisTemplate.delete(redisKey);
        userInfoMapper.updateUserStatusById(userId.longValue(), "1");
        UnFreezingUser freezingUser = new UnFreezingUser();
        freezingUser.setCreated(System.currentTimeMillis());
        freezingUser.setUserId(userId);
        freezingUser.setReasonsForThawing(reasonsForThawing);
        mongoTemplate.save(freezingUser);
        return "session";
    }

    @Override
    public Boolean queryById(long userId, Integer type) {
        Query query = new Query(Criteria.where("userId").is(userId).
                and("freezingRange").is(type));
        return mongoTemplate.exists(query,FreezingUser.class);
    }
}


